package cn.itcast.goods.category.service;

import java.sql.SQLException;
import java.util.List;

import org.junit.runner.Request;

import com.sun.org.apache.regexp.internal.recompile;

import cn.itcast.goods.book.dao.BookDao;
import cn.itcast.goods.category.dao.CategoryDao;
import cn.itcast.goods.category.doamin.Category;

public class CategoryService {

	private CategoryDao categoryDao=new CategoryDao();
	private BookDao bookDao = new BookDao();
	//查询所有的分类
	public List<Category> findAll(){
		try {
			return categoryDao.findAll();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	public void add(Category category) {
		// TODO Auto-generated method stub
		try {
		   categoryDao.add(category);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 查询所有的一级分类
	 * @return
	 */
	public List<Category> findByParents() {
		// TODO Auto-generated method stub
		try {
			return categoryDao.findByParents();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 加载一级分类
	 * @param cid
	 * @return
	 */
	public Object load(String cid) {
		
		try {
			return categoryDao.load(cid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 编辑一级分类
	 * @param category
	 */
	public void edit(Category category) {
		// TODO Auto-generated method stub
	    try { 
			categoryDao.edit(category);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e); 
		}
	}
	
	/**
	 * 刪除一級分類
	 * @param cid
	 */
	public void deleteOneLevel(String cid) {
		// TODO Auto-generated method stub
		try {
			int count = categoryDao.findChildrenCount(cid);
			if(count >0)
			{
				throw new CategoryException("删除一级分类失败，该分类下还存在子类，不能删除！");
			}
			categoryDao.delete(cid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 删除二级分类
	 * @param cid
	 */
	public void deleteTwoLevel(String cid) {
		// TODO Auto-generated method stub
		int count;
		try {
			count = bookDao.findCountByCategory(cid);
			if(count>0)
			{
				throw new CategoryException("删除二级分类失败，该分类下还存在图书，不能删除！");
			}
			categoryDao.delete(cid);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
		
	}
	/**
	 * 查找一级分类下的所有二级分类
	 * @param pid
	 * @return
	 */
	public List<Category> findChildren(String pid) {
		// TODO Auto-generated method stub
		try {
			 return categoryDao.findChildren(pid);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}
}
